package crud

import (
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ PermissionsModel = (*customPermissionsModel)(nil)

type (
	// PermissionsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPermissionsModel.
	PermissionsModel interface {
		permissionsModel
		CountAll(ctx context.Context) (int64, error)
		FindAll(ctx context.Context, page int64, pageSize int64) ([]*Permissions, error)
	}

	customPermissionsModel struct {
		*defaultPermissionsModel
	}
)

// NewPermissionsModel returns a model for the database table.
func NewPermissionsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) PermissionsModel {
	return &customPermissionsModel{
		defaultPermissionsModel: newPermissionsModel(conn, c, opts...),
	}
}

// CountAll counts all permissions.
func (m *customPermissionsModel) CountAll(ctx context.Context) (int64, error) {
	query := fmt.Sprintf("select count(*) from %s where `deleted_at` IS NULL", m.table)
	var count int64
	err := m.QueryRowNoCacheCtx(ctx, &count, query)
	return count, err
}

// FindAll finds all permissions with pagination.
func (m *customPermissionsModel) FindAll(ctx context.Context, page int64, pageSize int64) ([]*Permissions, error) {
	offset := (page - 1) * pageSize
	query := fmt.Sprintf("select %s from %s where `deleted_at` IS NULL limit ? offset ?", permissionsRows, m.table)
	var resp []*Permissions
	err := m.QueryRowsNoCacheCtx(ctx, &resp, query, pageSize, offset)
	return resp, err
}
